package com.rzjm.api.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rzjm.api.constant.ResponseCode;
import com.rzjm.api.entity.*;
import com.rzjm.api.service.*;
import com.rzjm.api.util.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;

/**
 *@Author: ZhouWei
 *@Description:  设备相关接口
 *@Date 2018-05-10
 */
@Component
@RequestMapping("/terminal")//url:模块/资源/{}/细分
public class TerminalController extends BaseController {

    @Resource
    private ShopService shopService;
    @Resource
    private UserService userService;
    @Resource
    private SysUserService sysUserService;
    @Resource
    private CkTerminalService ckTerminalService;
    @Resource
    private TerminalFittingService terminalFittingService;
    @Resource
    private TerminalTemperatureService temperatureService;
    @Resource
    private TerminalCheckRecordService terminalCheckRecordService;
    @Resource
    private TerminalRecordRepairService terminalRecordRepairService;
    @Resource
    private TerminalCheckRecordImgService terminalCheckRecordImgService;
    @Resource
    private TerminalRecordRepairImgService recordRepairImgService;
    @Resource
    private SysErrorService sysErrorService;
    @Resource
    private UserShopRelationService userShopRelationService;
    @Resource
    private SysDictService sysDictService;
    @Resource
    private WxTemplateService wxTemplateService;
    @Resource
    private UserMpService userMpService;

    @Value("${web.uploadPath}")
    private String uploadPath;//图片地址

    @Value("${web.appid_mp}")
    private String appidMp;//公众号appid
    @Value("${web.secret_mp}")
    private String secretMp;//公众号secret

    @Value("${web.imgprefix}")
    private String imgprefix;//图片地址

    /** 终端设备信息
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/detail",method = {RequestMethod.POST},produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject detail(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            logBefore(logger, "接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            String terminal_num = jsonRequest.containsKey("terminal_num") ? jsonRequest.getStr("terminal_num") : "";
            int fitting_id = jsonRequest.containsKey("fitting_id") ? jsonRequest.getInt("fitting_id") : 0;
            int shop_id = jsonRequest.containsKey("shop_id") ? jsonRequest.getInt("shop_id") : 1;
            if(shop_id == 0){
                shop_id = 1;
            }

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户信息不存在"),true,true);
            }

            SysUser sysUser = sysUserService.selectByUniqueColumn("user_id",user.getSysUserId());
            if(sysUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您未绑定企业人员"),true,true);
            }

            QueryWrapper<CkTerminal> qw1 = new QueryWrapper<>();
            qw1.eq("shop_id",shop_id);
            qw1.eq("terminal_num",terminal_num);
            CkTerminal terminal = ckTerminalService.getOne(qw1);
            if(terminal==null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您终端不存在"),true,true);
            }

            Shop shop = shopService.findById(terminal.getShopId());
            if(shop != null){
                terminal.setShopName(shop.getShopName());
            }

            if(sysUser.getUserType() >= 4){
                if(sysUser.getShopId() != terminal.getShopId()){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该终端不属于您的企业"),true,true);
                }
            }else if(sysUser.getUserType() == 2 || sysUser.getUserType() == 3){
                UserShopRelation relation = userShopRelationService.getRelation(terminal.getShopId(),sysUser.getUserId());
                if(relation == null){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该终端不属于您的企业"),true,true);
                }
            }
            List<SysDict> dictDOS = sysDictService.selectListByColumn("type","check-state");
            terminal.setDicts(dictDOS);
            map.put("terminal",terminal);
            List<String> fittingNames = new ArrayList<>();
            List<TerminalFitting> fittings = new ArrayList<>();
            if(fitting_id > 0){
                fittings = terminalFittingService.selectListByColumn("id",fitting_id);
            }else{
                fittings = terminalFittingService.selectListByColumn("terminal_id",terminal.getId());
            }
            if(fittings != null){
                for (TerminalFitting fitting : fittings){
                    fittingNames.add(fitting.getDeviceFittingName());
                }
            }
            map.put("fittings",fittings);
            map.put("fittings_name",fittingNames);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",map),true,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            sysErrorService.insertSelective("terminal/detail",e);
        }
        return result;
    }

    /**
     * 添加终端设备巡查记录
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/addCheck",method = {RequestMethod.POST},produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject addCheck(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            logBefore(logger, "接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            Integer terminal_id = jsonRequest.containsKey("terminal_id") ? jsonRequest.getInt("terminal_id") : 0;
            Integer check_state = jsonRequest.containsKey("check_state") ? jsonRequest.getInt("check_state") : 0;
            String check_result = jsonRequest.containsKey("check_result") ? jsonRequest.getStr("check_result") : "";
            Integer is_clean = jsonRequest.containsKey("is_clean") ? jsonRequest.getInt("is_clean") : 0;
            Integer fitting_id = jsonRequest.containsKey("fitting_id") ? jsonRequest.getInt("fitting_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户信息不存在"),true,true);
            }

            SysUser sysUser = sysUserService.selectByUniqueColumn("user_id",user.getSysUserId());
            if(sysUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您未绑定企业人员"),true,true);
            }

            CkTerminal terminal = ckTerminalService.getById(terminal_id);
            if(terminal == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该终端信息异常，请重试"),true,true);
            }

            Map<String,Object> map = DateUtil.getTodayTime();
            QueryWrapper<TerminalCheckRecord> qw = new QueryWrapper<>();
            qw.eq("terminal_id",terminal_id);
            qw.eq("wx_user_id",user_id);
            qw.eq("is_del",0);
            qw.eq("is_clean",is_clean);
            if(is_clean == 2){//如果是保养操作，要看保养点的保养记录条数
                qw.eq("fitting_id",fitting_id);
            }
            qw.between("create_time",map.get("begin_time"),map.get("end_time"));
            long count = terminalCheckRecordService.selectCountByQueryWrapper(qw);
            if(count >= 2){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该终端今天已提报过信息"),true,true);
            }

            TerminalCheckRecord record = new TerminalCheckRecord();
            record.setCheckState(check_state);
            record.setWxUserId(user.getId());
            record.setShopId(terminal.getShopId());
            record.setIsClean(is_clean);
            record.setCreateTime(new Date());
            record.setCheckResult(check_result);
            record.setTerminalId(terminal_id);
            record.setIsDel(0);
            record.setFittingId(fitting_id);
            try{
                int ret  = terminalCheckRecordService.addRecord(record,terminal);
                if(ret > 0){
                    int record_id = record.getId();
                    if(check_state == 2){//报修
                        System.out.println("开始发送消息");
                        sendWxMsg(terminal,record,1);//发送推送消息
                        System.out.println("结束发送消息");
                    }
                    result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"上报成功",record_id),true,false);
                }else{
                    result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"上报失败"),true,true);
                }
            }catch (Exception ex){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"上报失败"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            sysErrorService.insertSelective("terminal/addCheck",e);
        }
        return result;
    }

    private void sendWxMsg(CkTerminal terminal, TerminalCheckRecord record, Integer template_type){
        try{
            String accessToken = wxTemplateService.getAccessToken(appidMp,secretMp, 1);
            QueryWrapper<SysUser> qw = new QueryWrapper<>();
            qw.eq("shop_id",terminal.getShopId())
                    .and(wrapper -> wrapper.eq("user_type", 4).or().eq("user_type", 6));
            List<SysUser> sysUsers = sysUserService.list(qw);
            if(sysUsers != null && sysUsers.size() > 0){
                String ok_ids = "",error_ids = "";
                for(SysUser sysUser : sysUsers){
                    List<User> users = userService.selectListByColumn("sys_user_id",sysUser.getUserId());
                    if(users != null){
                        for (User user :users){
                            if(user != null && sysUser.getIsSendMsg() == 1 && StrUtil.isNotEmpty(user.getUnionId())){
                                WxMsgTemplate template = null;
                                if(template_type == 1){//报修
                                    template = getTemplate(terminal,user,record.getCheckResult());
                                }else if(template_type == 3){//维修完成
                                    template = getRepairedTemplate(terminal,user,sysUser,record);
                                }
//                                System.out.println("模板消息：" + template.toString());
                                String param = net.sf.json.JSONObject.fromObject(template).toString();
                                JSONObject jsonObject = WxMessage.sendMsg(accessToken,param);
                                if(jsonObject != null){
                                    int errcode = jsonObject.getInt("errcode");
                                    if(errcode == 0) {//发送成功
                                        ok_ids += user.getId()+",";
                                    }else{//发送失败
                                        error_ids += user.getId()+",";
                                    }
                                    System.out.println("jsonObject:" + jsonObject.toString());
                                }
                            }
                        }
                    }
                }

                ok_ids = StringUtil.getSplitStr(ok_ids);
                error_ids = StringUtil.getSplitStr(error_ids);
                record.setSendMsgOkIds(ok_ids);
                record.setSendMsgErrorIds(error_ids);
                terminalCheckRecordService.updateById(record);
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage(), e);
            System.out.println("发送失败" + e.getMessage());
        }
    }

    private WxMsgTemplate getTemplate(CkTerminal terminal,User user,String check_result){
        WxMsgTemplate template = new WxMsgTemplate();
        WxTemplate wxTemplate = wxTemplateService.selectByUniqueColumn("template_type",1);
        UserMp userMp = userMpService.selectByUniqueColumn("unionid",user.getUnionId());
        if(userMp!=null){
            template.setTouser(userMp.getOpenid());
            template.setTemplate_id(wxTemplate.getTemplateId());
            template.setUrl("");
            Map<String, MsgTempData> m = new HashMap<String, MsgTempData>();

            MsgTempData first = new MsgTempData();
            first.setColor(wxTemplate.getFontColor());
            first.setValue("管理员您好，有设备出现报修警报");
            m.put("first",first);

            //设备名称
            MsgTempData keyword1 = new MsgTempData();
            keyword1.setColor(wxTemplate.getFontColor());
            keyword1.setValue(terminal.getTerminalName());
            m.put("keyword1",keyword1);

            //设备编号
            MsgTempData keyword2 = new MsgTempData();
            keyword2.setColor(wxTemplate.getFontColor());
            keyword2.setValue(terminal.getTerminalNum());
            m.put("keyword2",keyword2);

            //在线状态
            MsgTempData keyword3 = new MsgTempData();
            keyword3.setColor(wxTemplate.getFontColor());
            keyword3.setValue("设备在线");
            m.put("keyword3",keyword3);

            //最后时间
            MsgTempData keyword4 = new MsgTempData();
            keyword4.setColor(wxTemplate.getFontColor());
            keyword4.setValue(DateUtil.getTime());
            m.put("keyword4",keyword4);

            //设备状态
            MsgTempData keyword5 = new MsgTempData();
            keyword5.setColor(wxTemplate.getSpicalFontColor());
            keyword5.setValue("该设备存在异常报修，请及时处理");
            m.put("keyword5",keyword5);


            MsgTempData remark = new MsgTempData();
            remark.setColor(wxTemplate.getFontColor());
            remark.setValue(check_result);
            m.put("remark",remark);

            template.setData(m);
        }
        return template;
    }

    /** 终端设备上报记录列表
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/recordlist",method = {RequestMethod.POST},produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject recordlist(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            logBefore(logger, "接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int is_clean = jsonRequest.containsKey("is_clean") ? jsonRequest.getInt("is_clean") : 0;
            int pageindex = jsonRequest.containsKey("pageindex") ? jsonRequest.getInt("pageindex") : 1;
            int pagesize = jsonRequest.containsKey("pagesize") ? jsonRequest.getInt("pagesize") : 10;
            int check_state = jsonRequest.containsKey("check_state") ? jsonRequest.getInt("check_state") : -1;
            int offset = (pageindex - 1) * pagesize;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户信息不存在"),true,true);
            }
            List<TerminalCheckRecord> list = terminalCheckRecordService.getListBySysUserId(user,is_clean,check_state,offset,pagesize);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",list.size(),list),false,false);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            sysErrorService.insertSelective("terminal/recordlist",e);
        }
        return result;
    }

    /** 维修终端设备列表
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/repairlist",method = {RequestMethod.POST},produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject repairlist(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            logBefore(logger, "接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int pageindex = jsonRequest.containsKey("pageindex") ? jsonRequest.getInt("pageindex") : 1;
            int pagesize = jsonRequest.containsKey("pagesize") ? jsonRequest.getInt("pagesize") : 10;
            int state = jsonRequest.containsKey("state") ? jsonRequest.getInt("state") : -1;
            String keyword = jsonRequest.containsKey("keyword") ? jsonRequest.getStr("health") : "";

            int offset = (pageindex - 1) * pagesize;
            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户信息不存在"),true,true);
            }
            List<CkTerminal> list = ckTerminalService.getTerminalList(user,state,keyword,offset,pagesize);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",list.size(),list),false,false);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            sysErrorService.insertSelective("terminal/repairlist",e);
        }
        return result;
    }

    /** 预警的保养终端设备列表
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/health/warnlist",method = {RequestMethod.POST},produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject healthWarnlist(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            logBefore(logger, "接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int pageindex = jsonRequest.containsKey("pageindex") ? jsonRequest.getInt("pageindex") : 1;
            int pagesize = jsonRequest.containsKey("pagesize") ? jsonRequest.getInt("pagesize") : 10;

            int offset = (pageindex - 1) * pagesize;
            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户信息不存在"),true,true);
            }
            List<TerminalFitting> list = terminalFittingService.getWarningFittingPageByUserId(user,offset,pagesize);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",list.size(),list),false,false);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            sysErrorService.insertSelective("terminal/health/warnlist",e);
        }
        return result;
    }


    /** 保养终端设备列表
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/healthlist",method = {RequestMethod.POST},produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject healthlist(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            logBefore(logger, "接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int pageindex = jsonRequest.containsKey("pageindex") ? jsonRequest.getInt("pageindex") : 1;
            int pagesize = jsonRequest.containsKey("pagesize") ? jsonRequest.getInt("pagesize") : 10;
            int health = jsonRequest.containsKey("health") ? jsonRequest.getInt("health") : 0;
            String keyword = jsonRequest.containsKey("keyword") ? jsonRequest.getStr("keyword") : "";

            int offset = (pageindex - 1) * pagesize;
            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户信息不存在"),true,true);
            }
            List<TerminalFitting> list = terminalFittingService.getTerminalFittingList(user,health,keyword,offset,pagesize);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",list.size(),list),false,false);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            sysErrorService.insertSelective("terminal/repairlist",e);
        }
        return result;
    }


    /** 处理维修的详情界面
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/recordDetail",method = {RequestMethod.POST},produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject repaireDetail(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            logBefore(logger, "接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int record_id = jsonRequest.containsKey("record_id") ? jsonRequest.getInt("record_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户信息不存在"),true,true);
            }

            SysUser sysUser = sysUserService.selectByUniqueColumn("user_id",user.getSysUserId());
            if(sysUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您未绑定企业人员"),true,true);
            }

            TerminalCheckRecord record = terminalCheckRecordService.findById(record_id);
            if(record==null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该记录不存在"),true,true);
            }

            CkTerminal terminal = ckTerminalService.getById(record.getTerminalId());
            if(terminal == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该终端信息异常"),true,true);
            }


            List<TerminalCheckRecordImg> imgs = terminalCheckRecordImgService.selectListByColumn("record_id",record.getId());
            if(imgs!=null){
                imgs.forEach(img->{
                    img.setImgUrl(imgprefix +img.getImgUrl());
                });
            }
            record.setImgs(imgs);

            map.put("record",record);
            map.put("terminal",terminal);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",map),true,false);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            sysErrorService.insertSelective("terminal/recordDetail",e);
        }
        return result;
    }


    /** 维修终端设备列表
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/repair",method = {RequestMethod.POST},produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject repair(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            logBefore(logger, "接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int record_id = jsonRequest.containsKey("record_id") ? jsonRequest.getInt("record_id") : 0;
            String result_op = jsonRequest.containsKey("result") ? jsonRequest.getStr("result") : "";

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户信息不存在"),true,true);
            }

            SysUser sysUser = sysUserService.selectByUniqueColumn("user_id",user.getSysUserId());
            if(sysUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您未绑定企业人员"),true,true);
            }

            TerminalCheckRecord checkRecord = terminalCheckRecordService.findById(record_id);
            if(checkRecord == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该报修记录不存在"),true,true);
            }

            CkTerminal terminal = ckTerminalService.getById(checkRecord.getTerminalId());
            if(terminal == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该终端信息异常"),true,true);
            }

            try{
                int repair_id = ckTerminalService.repair(sysUser.getName(),result_op, terminal,checkRecord);
                if(repair_id > 0){
                    sendWxMsg(terminal,checkRecord,3);//发送推送消息
                    result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"处理成功",repair_id),true,false);
                }else{
                    result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"处理失败"),true,true);
                }
            }catch (Exception ex){
                ex.printStackTrace();
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"处理失败"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            sysErrorService.insertSelective("terminal/repair",e);
        }
        return result;
    }

    /**
     *  维修完成的推送消息
     * @param terminal
     * @param user
     * @param record
     * @return
     */
    private WxMsgTemplate getRepairedTemplate(CkTerminal terminal, User user, SysUser sysUser, TerminalCheckRecord record){
        WxMsgTemplate template = new WxMsgTemplate();
        WxTemplate wxTemplate = wxTemplateService.selectByUniqueColumn("template_type",3);
        UserMp userMp = userMpService.selectByUniqueColumn("unionid",user.getUnionId());
        if(userMp!=null){
            template.setTouser(userMp.getOpenid());
            template.setTemplate_id(wxTemplate.getTemplateId());
            template.setUrl("");
            template.setTopColor(wxTemplate.getFontColor());
            Map<String, MsgTempData> m = new HashMap<String, MsgTempData>();

            MsgTempData first = new MsgTempData();
            first.setColor(wxTemplate.getFontColor());
            first.setValue("管理员您好，" + terminal.getTerminalNum() + terminal.getTerminalName()+  "修复完毕通知");
            m.put("first",first);

            //维修人员
            MsgTempData keyword1 = new MsgTempData();
            keyword1.setColor(wxTemplate.getFontColor());
            keyword1.setValue(sysUser.getName());
            m.put("keyword1",keyword1);

            //联系电话
            MsgTempData keyword2 = new MsgTempData();
            keyword2.setColor(wxTemplate.getFontColor());
            keyword2.setValue(sysUser.getMobile());
            m.put("keyword2",keyword2);

            //完成时间
            MsgTempData keyword3 = new MsgTempData();
            keyword3.setColor(wxTemplate.getFontColor());
            keyword3.setValue(DateUtil.getTime());
            m.put("keyword3",keyword3);

            //报修原因
            MsgTempData keyword4 = new MsgTempData();
            keyword4.setColor(wxTemplate.getFontColor());
            keyword4.setValue(record.getCheckResult());
            m.put("keyword4",keyword4);

            MsgTempData remark = new MsgTempData();
            remark.setColor(wxTemplate.getSpicalFontColor());
            remark.setValue(terminal.getTerminalNum() + terminal.getTerminalName()+ "修复异常已处理完毕，请知悉");
            m.put("remark",remark);

            template.setData(m);
        }
        return template;
    }

    /**
     * 巡检记录的图片上传
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/uploadImg",method = {RequestMethod.POST, RequestMethod.GET},produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject uploadImg(@RequestParam("record_id") int record_id, HttpServletRequest request) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            TerminalCheckRecord record = terminalCheckRecordService.getById(record_id);
            if(record == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "记录不存在"), true, true);
            }
            System.out.println("record_id==" + record_id);

            // 创建一个通用的多部分解析器.
            CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
            // 设置编码
            commonsMultipartResolver.setDefaultEncoding("utf-8");
            // 判断是否有文件上传
            if (commonsMultipartResolver.isMultipart(request)) {//有文件上传
                //将request变成多部分request
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
                //获取multiRequest 中所有的文件名
                Iterator<String> iter = multiRequest.getFileNames();
                if (iter.hasNext()) {
                    Map<String, MultipartFile> maps = multiRequest.getFileMap();
                    for(String key : maps.keySet()) {
                        MultipartFile certurl = maps.get(key);
                        if (!certurl.isEmpty()) {
                            String prefix = certurl.getOriginalFilename().substring(certurl.getOriginalFilename().lastIndexOf(".") + 1);
                            if ("jpeg".equals(prefix) || "jpg".equals(prefix) || "png".equals(prefix)) {
                                String fileName = "record_img_" + new Date().getTime() + "." + prefix;// user_photo.getOriginalFilename();
                                try {
                                    byte[] byteImg = certurl.getBytes();
                                    if (byteImg != null) {
                                        //上传头像到OSS
                                        int upload_type = OssUtil.TYPE_TERMINAL_RECORD_PHOTOS;
                                        String img_key = OssUtil.getUploadPrefix(upload_type) + fileName;

                                        String filePath = uploadPath + img_key;
                                        FileOutputStream out = new FileOutputStream(filePath);
                                        out.write(certurl.getBytes());
                                        out.flush();
                                        out.close();

                                        TerminalCheckRecordImg img = new TerminalCheckRecordImg();
                                        img.setRecordId(record_id);
                                        img.setImgUrl(img_key);
                                        terminalCheckRecordImgService.save(img);
                                    }
                                } catch (IOException e) {
                                    result = Tools.getJson(new GsonResultBean<>(-4, "系统异常"), true, true);
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                }
            }
            return Tools.getJson(new GsonResultBean<>(ResponseCode.OK, "图片上传成功"), true, true);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            System.out.println(""+e.getMessage());
            sysErrorService.insertSelective("terminal/uploadImg",e);
        }
        return result;
    }

    /** 巡检记录的图片上传
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/uploadImgRepair",method = {RequestMethod.POST, RequestMethod.GET},produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject uploadImgRepair(@RequestParam("repair_id") int repair_id, HttpServletRequest request) throws Exception{
        JSONObject result = null;
        try{
            TerminalRecordRepair repair = terminalRecordRepairService.getById(repair_id);
            if(repair == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "记录不存在"), true, true);
            }
            System.out.println("repair_id==" + repair_id);

            // 创建一个通用的多部分解析器.
            CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
            // 设置编码
            commonsMultipartResolver.setDefaultEncoding("utf-8");
            // 判断是否有文件上传
            if (commonsMultipartResolver.isMultipart(request)) {//有文件上传
                //将request变成多部分request
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
                //获取multiRequest 中所有的文件名
                Iterator<String> iter = multiRequest.getFileNames();
                if (iter.hasNext()) {
                    Map<String, MultipartFile> maps = multiRequest.getFileMap();
                    for(String key : maps.keySet()) {
                        MultipartFile certurl = maps.get(key);
                        if (!certurl.isEmpty()) {
                            String prefix = certurl.getOriginalFilename().substring(certurl.getOriginalFilename().lastIndexOf(".") + 1);
                            if ("jpeg".equals(prefix) || "jpg".equals(prefix) || "png".equals(prefix)) {
                                String fileName = "repair_img_" + new Date().getTime() + "." + prefix;// user_photo.getOriginalFilename();
                                try {
                                    byte[] byteImg = certurl.getBytes();
                                    if (byteImg != null) {
                                        //上传头像到OSS
                                        int upload_type = OssUtil.TYPE_TERMINAL_REPAIR_PHOTOS;
                                        String img_key = OssUtil.getUploadPrefix(upload_type) + fileName;

                                        String filePath = uploadPath + img_key;
                                        FileOutputStream out = new FileOutputStream(filePath);
                                        out.write(certurl.getBytes());
                                        out.flush();
                                        out.close();

                                        TerminalRecordRepairImg img = new TerminalRecordRepairImg();
                                        img.setRepairId(repair_id);
                                        img.setImgUrl(img_key);
                                        recordRepairImgService.save(img);
                                    }
                                } catch (IOException e) {
                                    e.printStackTrace();
                                    return Tools.getJson(new GsonResultBean<>(-4, "系统异常"), true, true);
                                }
                            }
                        }
                    }
                }
            }
            return Tools.getJson(new GsonResultBean<>(ResponseCode.OK, "图片上传成功"), true, true);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            System.out.println(""+e.getMessage());
            sysErrorService.insertSelective("terminal/uploadImgRepair",e);
        }
        return result;
    }

}
